<script setup lang="ts">
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  option: {
    type: Object,
    default: () => ({})
  }
})
const chartDomRef = ref()
let chartInstance = null

watch(
  props,
  () => {
    if (chartInstance) {
      chartInstance.clear()
      chartInstance.setOption(props.option, { notMerge: true })
    }
  },
  { deep: true }
)

// 初始化
const initChart = () => {
  nextTick(() => {
    chartInstance = echarts.init(chartDomRef.value)
    chartInstance.setOption(props.option)
  })
}

let resizeObserver
const chartResizeObserver = () => {
  resizeObserver = new window.ResizeObserver((entries) => chartInstance?.resize())
  resizeObserver.observe(chartDomRef.value)
}

onMounted(() => {
  initChart()
  chartResizeObserver()
})

onUnmounted(() => {
  chartInstance?.dispose()
  chartInstance = null
  if (resizeObserver) resizeObserver.disconnect()
})
</script>

<template>
  <div ref="chartDomRef" :style="{ width: '100%', height: '100%' }"></div>
</template>

<style scoped></style>
